# coding:utf-8
from django.contrib.auth import authenticate
from token_auth.models import Token
from userinfo.models import UserProfile
from django.contrib.auth.models import User
from django.views.decorators.csrf import csrf_exempt
import json
from django.http import HttpResponse
from token_auth.utils import json_response, token_required
import ImageFile
from hlr_django import settings
from userinfo.models import Photo,Schedule, Voice
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response

from userinfo.serializers import ScheduleSerializer
from django.utils import timezone

# from userinfo.serializers import ScheduleSerializer



@csrf_exempt
def user(request):
     # 注册
    if request.method == 'POST':
        return register(request)

    # 设置用户
    if request.method == 'PUT':
        return update(request)

    # 获取主持人
    if request.method == 'GET':
        return find(request)

@csrf_exempt
def avatar(request):
    if request.method == 'POST':
        return update(request)
    else:
        return json_response({},status=400)


@csrf_exempt
@token_required
def update(request):

    token = request.token
    user = token.user
    user_profile = user.get_profile()


    avatar = request.FILES.get('avatar',None)
    if avatar is not None:


        avatar_name = user.username + '_avatar.PNG'

        user_profile.avatar.save(avatar_name,avatar)


        host = request.get_host()
        avatar = 'http://'+host+settings.MEDIA_URL+str(user_profile.avatar)
        return json_response({'avatar':avatar})
    new_password = request.REQUEST.get(u'newpassword',None)
    old_password = request.REQUEST.get(u'oldpassword',None)

    if new_password is not None and old_password is not None:
        my_user = authenticate(username=user.username, password=old_password)
        if my_user is not None:
            user.set_password(new_password)
            user.save()
            return json_response({})
        else:
            return json_response({'error':'原密码错误'},status=401)




    nick_name = request.REQUEST.get(u'nickname',None)

    if nick_name is not None:

        user_profile.nick_name = nick_name
        user_profile.save()
        return json_response({})

    sign = request.REQUEST.get(u'sign',None)

    if sign is not None:
        user_profile.sign = sign
        user_profile.save()

        return json_response({})
    return json_response({},status=401)

@csrf_exempt
def reset_password(request):
    phone = request.REQUEST.get('phone',None)
    passWd = request.REQUEST.get('password',None)

    if phone is not None and passWd is not None:
        try:
            user_profile = UserProfile.objects.get(phone=phone)
            user = user_profile.user
            user.set_password(passWd)
            user.save()
            return json_response({})
        except:
            return json_response({},status=404)
    return json_response({},status=401)
def register(request):
    password = request.REQUEST.get('password',None)

    nick_name = request.REQUEST.get('nickname',None)
    phone = request.REQUEST.get('phone',None)
    birth_day = request.REQUEST.get('birthday',None)
    print birth_day
    height = request.REQUEST.get('height',None)
    gender = request.REQUEST.get('gender',None)
    sign = request.REQUEST.get('sign',None)
    age = request.REQUEST.get('age',None)

    if password is not None \
            and nick_name is not None and birth_day is not None\
            and gender is not None \
            and age is not None and age.isdigit():
        user_profile_exist_list = UserProfile.objects.filter(phone=phone)
        if len(user_profile_exist_list)>0:
            return json_response({'error':'phone is exist'},status=410)

        users_list = User.objects.all()
        num_users = len(users_list)

        user = User(username= str(1000000+num_users),password=password)
        user.set_password(password)
        user.save()
        try:
            user_profile = UserProfile(user=user,nick_name= nick_name,phone=phone,birthday=birth_day,\
                                       height=height,gender=gender,age=age)
        except:
            user.delete()


        if sign is not None:
            user_profile.sign = sign
        user_profile.save()

        token, created = Token.objects.get_or_create(user=user)
        host = request.get_host()
        avatar = 'http://'+host+settings.MEDIA_URL+str(user_profile.avatar)
        return json_response({
            'token': token.token,
            'nickname': user_profile.nick_name,
            'sign':user_profile.sign,
            'gender':user_profile.gender,
            'avatar':avatar,
            'phone':user_profile.phone,
            'height':user_profile.height,
            'sign':'您什么都没留下'
            })


    else:
        return json_response({'error':'Invalid data'},status=400)

# 查找主持人

def find(request):
    host = request.get_host()
    nickname = request.REQUEST.get('nickname',None)
    username = request.REQUEST.get('username',None)


    if nickname is not None and len(nickname)>0:

        user_profile_list = UserProfile.objects.filter(nick_name=nickname)
        user_profile_response_list = []
        for user_profile in  user_profile_list:

            sign = ''
            if user_profile.sign is None:
                sign = '该用户比较懒，什么也没有留下'
            else:
                sign = user_profile.sign
            avatar = 'http://'+host+settings.MEDIA_URL+str(user_profile.avatar)
            dic = {'nickname':user_profile.nick_name,
                   'age':user_profile.age,
                   'phone':user_profile.phone,
                   'sign':sign,
                   'username':user_profile.user.username,
                   'avatar':avatar,
                   }

            user_profile_response_list.append(dic)
        return json_response({'user_list':user_profile_response_list})

    if username is not None and len(username)>0:

        user = User.objects.get(username=username)
        user_profile = UserProfile.objects.get(user=user)
        sign = user_profile.sign
        if sign is None:
            sign = '该用户什么都没有留下呢'

        avatar = 'http://'+host+settings.MEDIA_URL+str(user_profile.avatar)
        print avatar
        dic = {'nickname':user_profile.nick_name,
                'age':user_profile.age,
                'phone':user_profile.phone,
                'sign':sign,
                'username':user_profile.user.username,
                'avatar':avatar,
        }


        return json_response(dic)

    else:
        user_profile_list = UserProfile.objects.all().order_by('-fans')

        user_profile_response_list = []
        for user_profile in  user_profile_list:

            sign = ''
            if user_profile.sign is None:
                sign = '该用户比较懒，什么也没有留下'
            else:
                sign = user_profile.sign

            avatar = 'http://'+host+settings.MEDIA_URL+str(user_profile.avatar)
            print avatar

            dic = {'nickname':user_profile.nick_name,
                   'age':user_profile.age,
                   'phone':user_profile.phone,
                   'sign':sign,
                   'username':user_profile.user.username,
                   'avatar':avatar,
                   }

            user_profile_response_list.append(dic)
        return json_response({'user_list':user_profile_response_list})



@csrf_exempt
@token_required
def focus(request):
    if request.method == 'POST':
        return add(request)
    if request.method == 'GET':

        return get_collection(request)
    return json_response({})
def get_collection(request):
    token = request.token
    user = token.user
    user_profile = user.get_profile()
    collection = user_profile.collection.all()

    user_profile_response_list = []
    host = request.get_host()
    for item in collection:
        if item is user:
            continue
        user_profile_item = item.get_profile()
        sign = ''
        if user_profile_item.sign is None:
            sign = '该用户比较懒，什么也没有留下'
        else:
            sign = user_profile_item.sign
        avatar = 'http://'+host+settings.MEDIA_URL+str(user_profile_item.avatar)
        dic = {'nickname':user_profile_item.nick_name,
                'age':user_profile_item.age,
                'phone':user_profile_item.phone,
                'sign':sign,
                'username':user_profile_item.user.username,
                'avatar':avatar,
                }

        user_profile_response_list.append(dic)

    return json_response({'list':user_profile_response_list})


def add(request):
    username = request.REQUEST.get('username',None)

    if username is not None:
        user = User.objects.get(username=username)
        user_profile = user.get_profile()

        token = request.token
        my = token.user

        my_profile = my.get_profile()

        user_profile.fans.add(my)


        my_profile.collection.add(user)
        return json_response({})




    else:
        return json_response({},status=400)



@csrf_exempt

def voice(request):
    if request.method == 'GET':
        username = request.REQUEST.get(u'username',None)
        if username is not None:

            user = User.objects.get(username=username)
            request.user = user
            return get_others_voice(request)
        else:
            return get_my_voice(request)
    if request.method == 'POST':
        return update_my_voice(request)
@token_required
def get_my_voice(request):
    voice = Voice.objects.get(user=request.token.user)
    host = request.get_host()
    voice_path = 'http://'+host+settings.MEDIA_URL+str(voice.file_path)
    return json_response({'voice':voice_path})

def get_others_voice(request):
    voice = Voice.objects.get(user=request.user)
    host = request.get_host()
    voice_path = 'http://'+host+settings.MEDIA_URL+str(voice.file_path)

    return json_response({'voice':voice_path})
@token_required
def update_my_voice(request):
    voice = request.FILES.get('voice',None)
    if voice is not None:
        user_profile = request.token.user.get_profile()
        voices =Voice.objects.filter(user=request.token.user)
        if len(voices)>0:

            voices[0].file_path = voice

            voices[0].save()
        else:
            voice_new = Voice.objects.create(title='xx',file_path=voice,user=request.token.user)
            voice_new.save()

        host = request.get_host()

        return json_response({})
    return json_response({},status=401)
@csrf_exempt
def photo(request):

    if request.method=='GET':

        username = request.REQUEST.get('username',None)
        if username is not None:
            user = User.objects.get(username=username)
            request.user = user
            return get_others_photo(request)
        else:
            return get_my_photo(request)
    if request.method == 'POST':
        return add_photo(request)

@token_required
def add_photo(request):
    photo = request.FILES.get('photo',None)
    if photo is not None:
        new_photo = Photo(user=request.token.user,img=photo)
        new_photo.save()
        return json_response({})
    else:

        return json_response({},status=401)

def get_others_photo(request):
    host = request.get_host()
    photo_list = Photo.objects.filter(user=request.user)
    print request.user
    list_response = []
    for photo in photo_list:
        image = 'http://'+host+settings.MEDIA_URL+str(photo.img)
        dic = {'title':photo.title,
                'image':image,
                'pk':photo.pk}

        list_response.append(dic)
    return json_response({'photo':list_response})

@token_required
def get_my_photo(request):
    host = request.get_host()
    photo_list = Photo.objects.filter(user=request.token.user)
    list_response = []
    for photo in photo_list:
        image = 'http://'+host+settings.MEDIA_URL+str(photo.img)
        dic = {'title':photo.title,
                'image':image,
                'pk':photo.pk}

        list_response.append(dic)
    return json_response({'photo':list_response})

# 获取档期
@csrf_exempt
def schedule(request):

    if request.method == 'GET':
        username = request.REQUEST.get('username',None)

        if username is not None:
            request.user = User.objects.get(username=username)
            return get_others_schedules(request)
        return get_my_schedules(request)



    if request.method == 'POST':
        return update_schedule(request)

@token_required
def update_schedule(request):
    note = request.REQUEST.get(u'note',None)
    begin_time = request.REQUEST.get(u'beginTime',None)
    end_time = request.REQUEST.get(u'endTime',None)
    pk = request.REQUEST.get(u'pk',None)

    if note is not None and begin_time is not None \
        and end_time is not  None:
        if pk is not None:
            schedule = Schedule.objects.get(pk=pk)
            schedule.begin_time = begin_time
            schedule.end_time = end_time;
            schedule.note = note;
            schedule.save()
            return json_response({})

        print begin_time
        print end_time

        schedule = Schedule.objects.create(user=request.token.user,begin_time = begin_time,end_time=end_time,note=note)
        schedule.save()
        return json_response({})
    else:
        return json_response({},status=400)
def get_others_schedules(request):

    schedules = Schedule.objects.filter(user=request.user)
    list_response= []
    for schedule in schedules:

        current_time_zone = timezone.get_current_timezone()
        dic = {'beginTime':current_time_zone.normalize(schedule.begin_time).strftime("%Y-%m-%d %H:%I"),
               'endTime':current_time_zone.normalize(schedule.end_time).strftime("%Y-%m-%d %H:%I"),
               'note':schedule.note,
               'day':current_time_zone.normalize(schedule.begin_time).strftime("%Y-%m-%d"),
               'pk':schedule.pk}
        list_response.append(dic)

    return json_response({'schedules':list_response})
@token_required
def get_my_schedules(request):

    schedules = Schedule.objects.filter(user=request.token.user)
    list_response= []

    for schedule in schedules:

        current_time_zone = timezone.get_current_timezone()
        dic = {'beginTime':current_time_zone.normalize(schedule.begin_time).strftime("%Y-%m-%d %H:%I"),
               'endTime':current_time_zone.normalize(schedule.end_time).strftime("%Y-%m-%d %H:%I"),
               'note':schedule.note,
               'day':current_time_zone.normalize(schedule.begin_time).strftime("%Y-%m-%d"),
               'pk':schedule.pk}
        list_response.append(dic)

    return json_response({'schedules':list_response})


# 删除相册
@csrf_exempt
@token_required
def remove_photo(request):
    pk = request.REQUEST.get('pk',None)
    if pk is not None:
        photo = Photo.objects.get(pk=pk)
        photo.delete()
        return json_response({})
    else:
        return json_response({},status=401)


@csrf_exempt
@token_required
def collection(request):
    pass
